<?php
/**
 *  用户开通守护记录表
 * ds
 * 2020.08.13
 */
namespace App\Models\MainDB;

use Illuminate\Database\Eloquent\Model;

class MallProducts extends Model{

    protected $table = 'ln_mall_products';     //数据库内完整表名

    protected $primaryKey = 'id';    //主键名

    protected $fillable = [
        'id',      // 主键id
        'category_id',      //  所属类别
        'title',            //  产品名称 
        'add_time',         //  添加时间 
        'picture',         //  图片 
        'special',         //  动态图 
        'on_sale',         //  是否出售1是2否 
        'show_type',         //  1公屏位置2全屏 
    ];

    public $timestamps = false;

    public function mall_orders()
    {
        return $this->hasOne('App\Models\MainDB\MallOrders', 'product_id', 'id');
    }

    public   function  mall_categories(){
        return $this->hasOne('App\Models\MainDB\MallCategories','id','category_id');
    }


    public  function  mall_products_price(){
        return $this->hasMany('App\Models\MainDB\MallProductsPrice','product_id','id');
    }

    public  function  one_mall_products_price(){
        return $this->hasOne('App\Models\MainDB\MallProductsPrice','product_id','id');
    }

    public function getProductList($cates = [])
    {
        $list = $this
            ->select('id as product_id', 'title as product_name')
            ->whereIn('category_id', array_keys($cates))
            ->where('on_sale', 1)
            ->get();
        return $list;
    }

    //查询某分类下的推荐商品数量
    public function getRecommendCountByCategoryId($categoryId, $onSale = 1)
    {
        return $this
            ->where('on_sale', $onSale)
            ->where(function ($query) use ($categoryId) {
                if (is_array($categoryId)) {
                    $query->whereIn('category_id', $categoryId);
                } else {
                    $query->where('category_id', $categoryId);
                }
            })
            ->where('is_recommend', 1)
            ->count();
    }

}